import { Modal, Button, Form, Select, DatePicker, Cascader, Drawer, Input, Upload, message } from 'antd';
import type { CascaderProps } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { skillTypeList, getCoreRegion } from '@/api/user';
import moment from 'moment'; //引入富文本编辑器
import BraftEditor from 'braft-editor';
// 引入编辑器样式
import 'braft-editor/dist/index.css';
import './index.scss';
import { addArticle, updateArticleId, uploadPresignedUrl } from '@/api/article';
import ReactQuill from 'react-quill';
// const fs = require('fs');
// import fs from 'fs';
import 'quill/dist/quill.snow.css'; // 引入 snow 主题的样式文件
import axios from 'axios';
interface Option {
    value?: string | number | null;
    label: React.ReactNode;
    children?: Option[];
    isLeaf?: boolean;
}
// const FilterModal = (props: { open: boolean; onCancel: any }) => {
const FilterModal = (props: any) => {
    const { open, onCancel, onConfirm, currentInfo, typeFlag } = props;
    console.log(currentInfo, '传过来的');
    const [filterForm] = Form.useForm();
    const { RangePicker } = DatePicker;
    // 确认按钮的loading状态
    const [confirmLoading, setConfirmLoading] = useState(false);
    const onFinish = (values: any) => {
        console.log(values, 9);
        //
    };
    useEffect(() => {
        if (open) {
            if (typeFlag === 'add') {
                filterForm.resetFields();
                setDefaultValueDetail(BraftEditor.createEditorState('<p></p>'));
                setArticleDetailContent(BraftEditor.createEditorState('<p></p>'));
            }
        }
    }, [open]);
    const [skillList, setSkillList] = useState<
        {
            eqSkillTypeDesc: string;
            eqSkillTypeId: string;
            eqSkillTypeName: string;
            value: string;
            label: string;
        }[]
    >([]);
    useEffect(() => {
        getSkill();
    }, []);
    // close按钮
    const closeModal = () => {
        if (typeFlag === 'add') {
            filterForm.resetFields();
            onCancel();
        } else {
            setEditFlag(false);
            filterForm.resetFields();
        }
    };
    // 关闭弹框
    const onCloseModal = () => {
        filterForm.resetFields();
        onCancel();
    };
    const filterOver = () => {
        const obj1 = filterForm.getFieldsValue();
        console.log(obj1, articleDetail);
        const obj = {
            // ...currentInfo,
            // obj1,
            articleTitle: obj1.articleTitle || currentInfo.articleTitle,
            eqSkillTypeId: obj1.eqSkillTypeId || currentInfo.eqSkillTypeId,
        };
        console.log(obj, obj1, articleDetail, obj.articleTitle);
        setTimeout(() => {
            if (obj.articleTitle == undefined || obj.articleTitle == '') {
                message.error('Please enter article title');
                return;
            }
            if (obj.eqSkillTypeId == undefined || obj.eqSkillTypeId == '') {
                message.error('Please enter article relationship skills');
                return;
            }
            if (!articleDetail || articleDetail == undefined || articleDetail === '<p></p>') {
                message.error('Please enter article details');
                return;
            }
            setConfirmLoading(true);
            if (typeFlag === 'add') {
                const params = {
                    eqSkillTypeId: obj.eqSkillTypeId,
                    articleTitle: obj.articleTitle,
                    articleDetail: articleDetail,
                };
                // 新增
                addArticle(params).then(res => {
                    setConfirmLoading(false);
                    onConfirm();
                });
            } else {
                const updateParams = {
                    eqSkillTypeId: obj.eqSkillTypeId || currentInfo.eqSkillTypeId,
                    articleTitle: obj.articleTitle || currentInfo.articleTitle,
                    articleDetail: articleDetail,
                    articleId: currentInfo.eqArticleId,
                };
                console.log(updateParams, articleDetail, currentInfo);
                // 编辑
                updateArticleId(updateParams).then(res => {
                    setConfirmLoading(false);
                    console.log(res);
                    onConfirm();
                });
            }
        }, 100);
    };
    //富文本组件内容
    // const [articleDetailContent, setArticleDetailContent] = useState<any>(
    //     BraftEditor.createEditorState(currentInfo.articleDetail || '<p></p>')
    // );
    const [defaultValueDetail, setDefaultValueDetail] = useState<any>(BraftEditor.createEditorState(null));
    useEffect(() => {
        if (currentInfo && currentInfo.articleDetail) {
            const editorContent = BraftEditor.createEditorState(currentInfo.articleDetail);
            setArticleDetailContent(editorContent);
            setArticleDetail(currentInfo.articleDetail);
        }
        console.log(typeFlag);

        if (typeFlag === 'add') {
            setEditFlag(true);
        } else {
            setEditFlag(false);
        }
    }, [currentInfo, typeFlag]);
    // 富文本组件内容
    const [articleDetailContent, setArticleDetailContent] = useState<any>(BraftEditor.createEditorState(null));

    //富文本输出的HTML
    // const [articleDetail, setArticleDetail] = useState<any>('<p></p>');
    const [articleDetail, setArticleDetail] = useState<any>('<p></p>');
    // useEffect(() => {
    //     if (currentInfo && currentInfo.articleDetail) {
    //         // console.log('执行这里', currentInfo.articleDetail);
    //         // const htmlString = BraftEditor.createEditorState(currentInfo.articleDetail);
    //         // // setArticleDetailContent(editorContent);
    //         // // const htmlString = '<p>Hello World11!</p>';
    //         // // 将HTML字符串转换为编辑器所需要的EditorState实例
    //         // const editorState = BraftEditor.createEditorState(htmlString);
    //         // // const string = JSON.stringify(infoObj.articleDetail);
    //         // const string = JSON.stringify(infoObj.eqArticleId);
    //         // const editorState = BraftEditor.createEditorState(string);
    //         // // const editorState = BraftEditor.createFromString(string);
    //         // console.log(infoObj.articleDetail);
    //         // console.log(editorState);
    //         const infoObj = JSON.parse(JSON.stringify(currentInfo));
    //         console.log('执行这里', infoObj.articleDetail);
    //         const editorContent = BraftEditor.createEditorState(infoObj.articleDetail);
    //         setArticleDetailContent(editorContent);
    //     }
    // }, [currentInfo.articleDetail]);
    /**
     * @Author: YuKi
     * @description: 处理富文本框显示数据
     * @param {Object} value 富文本框内容
     * @return {*}
     */
    const handleEditorState = (value: any) => {
        setArticleDetailContent(value); //必须要有这一步
        setArticleDetail(value.toHTML()); //获取富文本框里面的内容
    };

    const getSkill = () => {
        const params = {};
        skillTypeList(params).then((res: any) => {
            res.length > 0 &&
                res.map((item: any) => {
                    item.value = item.eqSkillTypeId;
                    item.label = item.eqSkillTypeName;
                });
            setSkillList(res);
        });
    };
    const formItems = [
        {
            type: 'input',
            label: 'Article title',
            key: 'articleTitle',
            options: [],
            value: currentInfo.articleTitle || '',
            placeholder: 'Enter the article title',
        },
        {
            type: 'select',
            label: 'Relationship skills',
            key: 'eqSkillTypeId',
            options: skillList,
            value: currentInfo.eqSkillTypeId || '',
            placeholder: 'Enter the relationship skill',
        },
    ];
    // 富文本编辑器的媒体（图片、视频）上传功能，调用我们自己这边的api上传到我们这边的服务器
    const handleMediaUpload = (params: any) => {
        const { file, progress, success, error } = params;
        const reader = new FileReader();
        reader.onload = e => {
            const arrayBuffer = e.target?.result as ArrayBuffer;
            const blob = new Blob([arrayBuffer], { type: file.type });
            const fileTypeList = file.name.split('.');
            const fileType = fileTypeList.length > 1 ? `.${fileTypeList[1]}` : '.png';
            // 获取认证信息
            const token = sessionStorage.getItem('frieneed-admin-satoken');
            uploadPresignedUrl({ extName: fileType || 'png' })
                .then((res: any) => {
                    const url = res.url; // 假设服务器返回的URL在response.data.url中
                    axios
                        .put(url, blob, {
                            headers: {
                                ...res.headers,
                                'Accept-Language': 'en-US',
                                'Frieneed-admin-satoken': token || '', // 根据实际情况设置请求头
                                'Content-Type': res.headers['Content-Type'],
                                Date: res.headers['Date'],
                            },
                            onUploadProgress: progressEvent => {
                                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                                progress(percentCompleted);
                            },
                        })
                        .then(res1 => {
                            console.log(res1);
                            // 注意，此接口比较特殊，res1不会返回图片地址，图片地址是res1里面的url（去掉问号后面一段，只要前面一段，就是图片地址）
                            const picUrlList = res.url.split('?');
                            const picUrl = picUrlList.length > 0 ? picUrlList[0] : '';
                            success({
                                url: picUrl,
                                meta: {
                                    id: '', // 根据实际情况填充
                                    title: file.name,
                                    alt: file.name,
                                    loop: false,
                                    autoPlay: false,
                                    controls: true,
                                    poster: '',
                                    width: '95%', // 设置宽度为100%
                                    height: 'auto', // 设置高度为auto
                                    // style: 'max-width: 100%; height: auto;', // 添加样式
                                },
                            });
                        })
                        .catch(error => {
                            console.error('Upload failed:', error);
                            error({ code: 'UPLOAD_FAILED', message: 'Failed to upload the file' });
                        });
                })
                .catch(error => {
                    console.error('Upload failed:', error);
                    error({ code: 'UPLOAD_FAILED', message: 'Failed to upload the file' });
                });
        };

        reader.onerror = e => {
            console.error('File could not be read: ' + e.target?.error?.code);
            error({ code: 'READ_FAILED', message: 'File could not be read' });
        };

        reader.readAsArrayBuffer(file);
    };

    const [controlsList, setControlsList] = useState<any[]>([
        // 'undo',
        // 'redo',
        // 'separator',
        {
            key: 'font-size', // 使用key来指定控件类型
            title: '16', // 自定义控件title
            // text: '点我选择字号', // 使用自定义文案来代替默认图标(B)，此处也可传入jsx
        },
        // 'line-height',
        // 'letter-spacing',
        'separator',
        'text-color',
        'bold',
        'italic',
        'underline',
        'strike-through',
        'separator',
        'superscript',
        'subscript',
        'remove-styles',
        'emoji',
        // 'separator',
        // 'text-indent',
        'text-align',
        'separator',
        {
            key: 'headings', // 使用key来指定控件类型
            title: 'h1', // 自定义控件title
            // text: '点我选择字号', // 使用自定义文案来代替默认图标(B)，此处也可传入jsx
        },
        'list-ul',
        'list-ol',
        'blockquote',
        'code',
        'separator',
        'link',
        'separator',
        'hr',
        'separator',
        'media',
        'separator',
        'clear',
    ]);
    const extendControlsContent = [
        // {
        //     key: 'antd-uploader',
        //     type: 'component',
        //     component: (
        //         <Upload
        //             accept="*"
        //             showUploadList={false}
        //             onChange={uploadHandler}
        //             action={environment().backendUrl + '/sysfrontpicture/upload'}
        //         >
        //             <button type="button" className="control-item button upload-button" data-title="插入图片">
        //                 上传图片
        //             </button>
        //         </Upload>
        //     ),
        // },
    ];
    //   const uploadHandler = (info) => {
    //     if (info.file.status === 'done') {
    //       let data = info.file.response;
    //       if (data.code === requestCode.successCode) {
    //         setEditorcontent(
    //           ContentUtils.insertMedias(editorcontent, [
    //             {
    //               type: 'IMAGE',
    //               url: info.file.response.data.url,
    //             },
    //           ]),
    //         );
    //       } else {
    //         message.error('图片上传失败');
    //       }
    //     } else if (info.file.status === 'error') {
    //       message.error(`${info.file.name} file upload failed.`);
    //     }
    //   };
    const [isEditFlag, setEditFlag] = useState(false);
    /**
     * 改变此页面是否是编辑状态
     */
    const editChange = () => {
        if (currentInfo && currentInfo.articleDetail) {
            const editorContent = BraftEditor.createEditorState(currentInfo.articleDetail);
            setArticleDetailContent(editorContent);
            setDefaultValueDetail(editorContent);
        }
        const flag = !isEditFlag;
        setEditFlag(flag);
    };
    //   从这里结束 级联选择器
    return (
        <Drawer
            width={780}
            maskClosable={true}
            placement="right"
            open={open}
            closable={false}
            className="deawerBox"
            // onClose={closeModal}
        >
            <div className="deawerTopBox flex-between">
                {typeFlag === 'add' ? (
                    <div>Add article</div>
                ) : (
                    <div> {isEditFlag ? 'Edit article' : 'Article details'}</div>
                )}
                <div>
                    <img src={require('@/assets/images/close-modal.png')} onClick={onCloseModal} alt="" />
                </div>
            </div>
            {isEditFlag ? (
                <div>
                    <Form
                        name="filter-form"
                        className="filter-form"
                        form={filterForm}
                        layout="vertical"
                        onFinish={onFinish}
                        validateTrigger="onBlur"
                        autoComplete="off"
                    >
                        <div>
                            {formItems.map(i => {
                                return (
                                    <Form.Item label={i.label} name={i.key} key={i.key}>
                                        {i.type === 'select' ? (
                                            <Select
                                                className="form-select selectBox"
                                                suffixIcon={
                                                    <img
                                                        src={require('@/assets/images/arrowDown.png')}
                                                        style={{ width: 20, height: 20 }}
                                                    />
                                                }
                                                placeholder={i.placeholder}
                                                defaultValue={i.value}
                                            >
                                                {i.options.map(o => {
                                                    return (
                                                        <Select.Option value={o.value} key={o.value}>
                                                            {o.label}
                                                        </Select.Option>
                                                    );
                                                })}
                                            </Select>
                                        ) : (
                                            <Input defaultValue={i.value} placeholder={i.placeholder} />
                                        )}
                                    </Form.Item>
                                );
                            })}

                            <Form.Item label="Article details" name="Article details">
                                {/* BraftEditor.createEditorState('<p><span style="color:#c0392b"><u><em>我们都有一个家，</em></u></span></p><p><span style="color:#c0392b"><u><em>名字叫中国；</em></u></span></p><p><span style="color:#c0392b"><u><em>兄弟姐妹都很多，</em></u></span></p><p><span style="color:#c0392b"><u><em>景色也不错；</em></u></span></p>') */}
                                {/* <BraftEditor
                                className="my-editor"
                                value={articleDetailContent}
                                // defaultValue={BraftEditor.createEditorState(currentInfo.articleDetail)}
                                // defaultValue={articleDetailContent}
                                defaultValue={BraftEditor.createEditorState(currentInfo.articleDetail)}
                                onChange={handleEditorState}
                                controls={controlsList}
                                contentStyle={{
                                    height: 210,
                                    boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)',
                                    border: '1px solid black',
                                }}
                            /> */}
                                <BraftEditor
                                    className="my-editor"
                                    value={articleDetailContent} // 使用 value 属性
                                    onChange={handleEditorState}
                                    defaultValue={defaultValueDetail}
                                    controls={controlsList}
                                    media={{
                                        uploadFn: handleMediaUpload, // 自定义上传处理函数
                                    }}
                                    // extendControls={extendControlsContent}
                                    contentStyle={{
                                        height: 210,
                                        boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)',
                                        border: '1px solid black',
                                    }}
                                />
                                {/* <ReactQuill
                                theme="snow"
                                value={
                                    '<p><span style="color:#c0392b"><u><em>我们都有一个家，</em></u></span></p><p><span style="color:#c0392b"><u><em>名字叫中国；</em></u></span></p><p><span style="color:#c0392b"><u><em>兄弟姐妹都很多，</em></u></span></p><p><span style="color:#c0392b"><u><em>景色也不错；</em></u></span></p>'
                                }
                                onChange={setValue}
                            /> */}
                            </Form.Item>
                        </div>
                    </Form>
                    <div className="drawerFooterBox flex-end">
                        <Button onClick={closeModal} disabled={confirmLoading}>
                            Cancel
                        </Button>
                        <Button loading={confirmLoading} type="primary" onClick={filterOver}>
                            Save
                        </Button>
                    </div>
                </div>
            ) : (
                <div>
                    <div className="detailBox">
                        <div className="detailTitle">{currentInfo.articleTitle}</div>
                        <div className="detailSkillType">{currentInfo.eqSkillTypeName}</div>
                        <div className="htmlBox">
                            <div dangerouslySetInnerHTML={{ __html: currentInfo.articleDetail }} />
                        </div>
                    </div>
                    <div className="flex-end">
                        <Button
                            className="orangeBtn ml-10"
                            type="primary"
                            htmlType="submit"
                            onClick={() => editChange()}
                        >
                            Edit
                        </Button>
                    </div>
                </div>
            )}
        </Drawer>
    );
};
export default FilterModal;
